<?php


namespace App\Dao;

use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use App\Model\UserEmployer;

class UserEmployerDao extends AbstractDao
{
    public function where(array $where): \Hyperf\Database\Model\Builder
    {
        $builder = UserEmployer::query();
        foreach ($where as $field => $value) {
            switch ($field) {
                case 'keywords':
                    $builder->whereHas('user', function ($query) use ($value) {
                        $query->where('id', $value);
                        $query->orwhere('phone', $value);
                        $query->orwhere('nickname', 'like', '%' . $value . '%');
                    });
                    break;
                case 'cooperative_ids':
                    $builder->whereIn('cooperative_id', $value);
                    break;
                default:
                    $builder->where($field, $value);
            }
        }
        return $builder;
    }

    /**
     * @param array $where
     * @return UserEmployer
     */
    public function firstOrFail(array $where): UserEmployer
    {
        /** @var UserEmployer $userEmployer */
        $userEmployer = $this->first($where);
        if (!$userEmployer) {
            throw new BusinessException(ErrorCode::USER_EMPLOYER_NOT_FOUND);
        }
        return $userEmployer;
    }

    /**
     * @param array $data
     * @return UserEmployer
     */
    public function create(array $data): UserEmployer
    {
        $userEmployer = $this->first(['user_id' => $data['user_id']]);
        if ($userEmployer) {
            throw new BusinessException(ErrorCode::USER_EMPLOYER_EXISTS);
        }
        $userEmployer = new UserEmployer();
        $userEmployer->user_id = $data['user_id'];
        $userEmployer->cooperative_id = $data['cooperative_id'];
        $userEmployer->status = $data['status'];
        $userEmployer->credit_point = $data['credit_point'];
        $userEmployer->shop_point = $data['shop_point'];
        $userEmployer->save();
        return $userEmployer;
    }
}